package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.entity.PageResult;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.pojo.TravelItem;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public List<TravelItem> getGroupItem() {
        List<TravelItem> travelItems = travelGroupDao.getGroupItem();
        return travelItems;
    }

    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
        travelGroupDao.add(travelGroup);
        addSetGroupItem(travelGroup.getId(),travelItemIds);
    }

    @Override
    public void addSetGroupItem(Integer travelGroup_id, Integer[] travelItemIds) {
        if(travelItemIds.length > 0){
            Map<String,Integer> map = new HashMap<>();
            for (Integer travelItemId : travelItemIds){
                map.put("travelGroupId",travelGroup_id);
                map.put("travelItemId",travelItemId);
                travelGroupDao.addSetGroupItem(map);
            }
        }else{
            return;
        }
    }

    @Override
    public PageResult get(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage,pageSize);

        Page<TravelGroup> page = travelGroupDao.get(queryString);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    @Override
    public void delete(Integer id) {
        travelGroupDao.delete(id);
    }

    @Override
    public int selectGroupItem(Integer id) {
        int i = travelGroupDao.selectGroupItem(id);

        return i;
    }

    @Override
    public TravelGroup selectGroupId(Integer id) {
        return travelGroupDao.selectGroupId(id);
    }

    @Override
    public List<Integer> findTravelItemIdByTravelgroupId(Integer id) {
        return travelGroupDao.findTravelItemIdByTravelgroupId(id);
    }

    @Override
    public void update(TravelGroup travelGroup, Integer[] travelItemIds) {
        travelGroupDao.update(travelGroup);

        if(travelItemIds.length > 0){
            travelGroupDao.deleteGroupItem(travelGroup.getId());

            for (Integer travelItemId : travelItemIds){
                Map<String, Integer> map = new HashMap<>();
                map.put("travelGroupId",travelGroup.getId());
                map.put("travelItemId",travelItemId);
                travelGroupDao.addSetGroupItem(map);
            }

        }

    }
}
